from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

from google.appengine.api import memcache

import wsgiref.handlers
import logging, os

import db

class MainPage(webapp.RequestHandler):
    def get(self):
        rt = self.get_resttype()
        rc = db.RestCountry.all()
        if (not rt.count()) or (not rc.count()):self.insertData()
        
        temp_var = {"resttype" : rt}
            
        path = os.path.join(os.path.dirname(__file__), 'templates/index.html')    
        self.response.out.write(template.render(path, temp_var))
    
    def get_resttype(self):  
        data = memcache.get("key")  
        if data is not None:    
            return data  
        else:    
            data = db.RestType.all() 
            memcache.add("key", data, 60)    
            return data  
      
    def insertData(self):
        logging.info("[RestType]import data")
        for line in file("codetable/RestType.txt"):
            r = line.split(",")
            rt = db.RestType()
            rt.rest_type_short = r[1]
            rt.rest_type_big5 = r[2]
            rt.rest_type_eng = r[3] 
            rt.rest_type_gb = r[4]
            rt.put()
        logging.info("[RestContry]import data")
        country = []
        for line in file("codetable/RestContry.txt"):
            r = line.split(",")
            rc = db.RestCountry()
            rc.country_name_short = r[1]
            rc.country_name_big5 = r[2]
            rc.country_name_eng = r[3]
            rc.country_name_gb = r[4]
            rc.put()
            country[rc[0]] = rc.key()
        logging.info("[RestCity]import data")
        for line in file("codetable/RestCity.txt"):
            r = line.split(",")
            rc = db.RestCity()
            rc.city_country = country[r[0]]
            rc.city_name_short = r[1]
            rc.city_name_big5 = r[2]
            rc.city_name_eng = r[3]
            rc.city_name_gb = r[4]
            rc.put()
        

def main():
    application = webapp.WSGIApplication(
                                       [('/', MainPage)],
                                       debug=True)
    wsgiref.handlers.CGIHandler().run(application)



if __name__ == "__main__":
    main()